<template>
  <view class="template-preferred tn-safe-area-inset-bottom">
    <!-- 顶部自定义导航 -->
    <tn-nav-bar :isBack="false" :bottomShadow="false" backgroundColor="#FFFFFF">
      <view class="" style="width: 72vw; overflow: hidden">

        <tn-tabs
          :list="platformOptions"
          :current="current"
          @change="tabChange"
          activeColor="#000"
          :bold="true"
          :fontSize="36"
        ></tn-tabs>
      </view>
    </tn-nav-bar>

    <view class="">
      <view class="tn-flex tn-flex-wrap tn-margin-sm">
        <block v-for="(item, index) in filteredContent" :key="index">
          <view
            class=""
            style="width: 50%"
            @click="tn('/preferredPages/product')"
          >
            <view
              class="tn-blogger-content__wrap"
              :class="{'expired': isExpired(item.shareTime)}"
              style="background-color: rgba(255, 255, 255, 0.6)"
            >
              <view
                class="image-picbook"
                :style="
                  'background-image:url(' +
                  $minApi.imgOrigin +
                  item.imagePath +
                  ')'
                "
              >
                <view class="image-book"> </view>
                <view class="expired-mark" v-if="isExpired(item.shareTime)">
                  <text>已过期</text>
                </view>
              </view>

              <view
                class="tn-blogger-content__label tn-text-justify tn-padding-sm"
              >
                <text class="tn-blogger-content__label__desc" v-if="item.platform === 'PIN_DUO_DUO'">
                  <template v-if="item.goodsInfo">
                    <view class="goods-info">
                      <text class="goods-title">{{ item.goodsInfo.title }}</text>
                      <text class="goods-price">¥{{ item.goodsInfo.price }}</text>
                      <text class="goods-sales">{{ item.goodsInfo.sales }}</text>
                    </view>
                  </template>
                  <template v-else>
                    {{ formatPddCommand(item.command) }}
                  </template>
                </text>
                <text class="tn-blogger-content__label__desc" v-else>{{
                  item.command || "暂无内容"
                }}</text>
              </view>

              <view
                class="tn-flex tn-flex-row-between tn-flex-col-center tn-padding-left-sm tn-padding-right-sm tn-padding-bottom-sm"
              >
                <view class="justify-content-item tn-text-center">
                  <view
                    class="tn-blogger-content__label__item tn-float-left tn-margin-right tn-bg-gray--light tn-round tn-text-sm tn-text-bold"
                  >
                    <view :class="{
                      'platform-icon': true,
                      'pdd-color': item.platform === 'PIN_DUO_DUO',
                      'taobao-color': item.platform === 'TAO_BAO',
                      'douyin-color': item.platform === 'DOU_YIN'
                    }">
                      <view :class="{
                        'tn-icon-shop': item.platform === 'PIN_DUO_DUO',
                        'tn-icon-cart': item.platform === 'TAO_BAO',
                        'tn-icon-video': item.platform === 'DOU_YIN'
                      }"></view>
                    </view>
                    {{ getPlatformLabel(item.platform) }}
                  </view>
                  <view
                    class="tn-blogger-content__label__item tn-float-left tn-margin-right tn-bg-gray--light tn-round tn-text-sm tn-text-bold"
                  >
                    <text
                      class="tn-icon-time tn-padding-right-xs tn-color-indigo"
                    ></text>
                    {{ formatTime(item.shareTime) }}
                  </view>
                </view>
              </view>
            </view>
          </view>
        </block>
      </view>
    </view>

    <view class="tn-tabbar-height"></view>
  </view>
</template>

<script>
export default {
  name: "Preferred",
  data() {
    return {
      cardCur: 0,
      current: 0,
      platformOptions: [],
      content2: [],
      page: 1,
      pageSize: 10,
      loadStatus: "loadmore",
      list: [],
    };
  },

  computed: {
    // 根据当前选中的平台过滤内容
    filteredContent() {
      if (!this.platformOptions.length) return this.content2;
      const currentPlatform = this.platformOptions[this.current]?.value;
      if (!currentPlatform) return this.content2;
      return this.content2;
    }
  },

  async mounted() {
    await this.getPlatformDict(); // 先获取平台数据
    this.getShareList(); // 再获取列表数据
  },

  methods: {
    // 处理拼多多口令，提取商品信息
    formatPddCommand(command) {
      if (!command) return '';
      // 匹配 "复制并打开拼多多APP，" 后面的内容，直到 "，仅剩" 或 "。" 为止
      const match = command.match(/复制并打开拼多多APP[，,](.+?)([，,]仅剩|。)/);
      if (match && match[1]) {
        return match[1].trim();
      }
      // 如果没有匹配到标准格式，返回原始内容
      return command;
    },

    // 获取平台标签
    getPlatformLabel(platform) {
      const labelMap = {
        'PIN_DUO_DUO': '拼多多',
        'TAO_BAO': '淘宝',
        'DOU_YIN': '抖音'
      };
      return labelMap[platform] || platform;
    },

    // 解析拼多多口令
    async parsePddCommand(command) {
      try {
        const res = await this.$minApi.parsePddCommand({
          command: command
        });
        
        if (res.success && res.data) {
          // 更新商品信息
          const index = this.content2.findIndex(item => item.command === command);
          if (index !== -1) {
            this.$set(this.content2[index], 'goodsInfo', {
              title: res.data.goods_name,
              price: res.data.min_group_price / 100,
              thumbnail: res.data.goods_thumbnail_url,
              sales: res.data.sales_tip,
            });
          }
        }
      } catch (error) {
        console.error('解析口令失败:', error);
      }
    },

    // 获取平台字典数据
    async getPlatformDict() {
      try {
        const response = await this.$minApi.getDict({
          dictCode: "GOU_WU_PING_TAI",
          status: true,
          pageSize: 100,
        });

        if (response?.success && response.data?.list) {
          this.platformOptions = response.data.list
            .sort((a, b) => a.sort - b.sort)
            .map((item) => ({
              label: item.label,
              value: item.value,
              name: item.label, // 添加name属性，因为tn-tabs组件可能需要这个属性
            }));
        }
      } catch (error) {
        console.error("获取平台字典数据失败:", error);
      }
    },

    // tab选项卡切换
    tabChange(index) {
      this.current = index;
      this.page = 1;
      this.getShareList();
    },

    // 跳转
    tn(e) {
      uni.navigateTo({
        url: e,
      });
    },

    // 获取拼团列表
    async getShareList() {
      try {
        const params = {
          page: this.page,
          pageSize: this.pageSize,
        };
        
        // 如果有选中的平台，添加平台参数
        if (this.platformOptions.length && this.platformOptions[this.current]) {
          params.platform = this.platformOptions[this.current].value;
        }
        
        const res = await this.$minApi.getShareList(params);
        if (res.success) {
          const list = res.data.list;
          
          // 处理拼多多的商品信息
          if (params.platform === 'PIN_DUO_DUO') {
            list.forEach(item => {
              if (item.command && !item.goodsInfo) {
                this.parsePddCommand(item.command);
              }
            });
          }
          
          if (this.page === 1) {
            this.content2 = list;
          } else {
            this.content2 = [...this.content2, ...list];
          }
        }
      } catch (error) {
        console.error("获取拼团列表失败:", error);
      }
    },

    // cardSwiper
    cardSwiper(e) {
      this.cardCur = e.detail.current;
    },

    // 瀑布流加载完毕事件
    handleWaterFallFinish() {
      this.loadStatus = "loadmore";
    },

    // 获取价格整数和小数部分
    getPrice(price) {
      const priceStr = String(price);
      if (priceStr.indexOf(".") !== -1) {
        return priceStr.split(".");
      } else {
        return [priceStr, "00"];
      }
    },

    // 下拉刷新
    onPullDownRefresh() {
      this.page = 1;
      this.getShareList().then(() => {
        uni.stopPullDownRefresh();
      });
    },

    // 触底加载更多
    onReachBottom() {
      this.page++;
      this.getShareList();
    },

    // 格式化时间
    formatTime(time) {
      if (!time) return "";
      const date = new Date(time);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hour = String(date.getHours()).padStart(2, "0");
      const minute = String(date.getMinutes()).padStart(2, "0");
      return `${year}-${month}-${day} ${hour}:${minute}`;
    },

    // 判断是否过期（24小时）
    isExpired(shareTime) {
      if (!shareTime) return false;
      const now = new Date().getTime();
      const shareDate = new Date(shareTime).getTime();
      return (now - shareDate) > 24 * 60 * 60 * 1000;
    },

    // 处理分享
    handleShare(item) {
      // 分享处理逻辑
    },
  },
};
</script>

<style lang="scss" scoped>
.template-preferred {
  // background-color: $tn-bg-gray-color;
  max-height: 100vh;
}
.tn-tabbar-height {
  min-height: 120rpx;
  height: calc(140rpx + env(safe-area-inset-bottom) / 2);
}

/* 商家 start */
.card-swiper {
  height: 260rpx !important;
  overflow: hidden;
  // background-color: #00C3FF;
}

.card-swiper swiper-item {
  width: 632rpx !important;
  left: -10rpx;
  box-sizing: border-box;
  overflow: initial;
  padding: 0 0rpx 40rpx 0;
}

.card-swiper swiper-item .swiper-item {
  width: 100%;
  display: block;
  height: 100%;
  transform: scale(1);
  transition: all 0.2s ease-in 0s;
}

.card-swiper swiper-item.cur .swiper-item {
  transform: none;
  transition: all 0.2s ease-in 0s;
}

.card-swiper swiper-item .swiper-item-text {
  margin-top: -210rpx;
  width: 100%;
  display: block;
  height: 100%;
  border-radius: 10rpx;
  transform: translate(30rpx, -80rpx) scale(0.8, 0.8);
  transition: all 0.6s ease 0s;
  overflow: hidden;
}

.card-swiper swiper-item.cur .swiper-item-text {
  margin-top: -270rpx;
  width: 100%;
  transform: translate(20rpx, 0rpx) scale(0.9, 0.9);
  transition: all 0.6s ease 0s;
}

/* 图标容器5 start */
.icon5 {
  &__item {
    // width: 30%;
    background-color: #ffffff;
    border-radius: 10rpx;
    padding: 0rpx;
    margin: 0rpx;
    transform: scale(1);
    transition: transform 0.3s linear;
    transform-origin: center center;

    &--icon {
      width: 100rpx;
      height: 100rpx;
      border-radius: 50%;
      margin-bottom: 18rpx;
      position: relative;
      z-index: 1;
    }
  }
}

/* 图标容器11 start */
.icon11 {
  &__item {
    width: 30%;
    background-color: #ffffff;
    border-radius: 10rpx;
    padding: 30rpx;
    margin: 20rpx 10rpx;
    transform: scale(1);
    transition: transform 0.3s linear;
    transform-origin: center center;

    &--icon {
      width: 100rpx;
      height: 100rpx;
      font-size: 60rpx;
      border-radius: 50%;
      margin-bottom: 18rpx;
      position: relative;
      z-index: 1;

      &::after {
        content: " ";
        position: absolute;
        z-index: -1;
        width: 100%;
        height: 100%;
        left: 0;
        bottom: 0;
        border-radius: inherit;
        opacity: 1;
        transform: scale(1, 1);
        background-size: 100% 100%;
        background-image: url(https://resource.tuniaokj.com/images/cool_bg_image/icon_bg.png);
      }
    }
  }
}

/* 瀑布流商品*/
.product__item {
  background-color: #ffffff;
  border-radius: 15rpx;
  overflow: hidden;
  margin: 0 15rpx 30rpx 15rpx;
  box-shadow: 0rpx 0rpx 30rpx 0rpx rgba(0, 0, 0, 0.07);

  .item {
    /* 图片 start */
    &__image {
      width: 100%;
      height: auto;
      background-color: #ffffff;
    }
    /* 图片 end */

    /* 内容 start */
    &__data {
      padding: 20rpx 20rpx;
    }

    /* 标题 start */
    &__title-container {
      text-align: justify;
      line-height: 38rpx;
      vertical-align: middle;
    }
    &__store-type {
      height: 28rpx;
      font-size: 20rpx;
      position: relative;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      padding: 0 4rpx;
      border-radius: 6rpx;
      white-space: nowrap;
      text-align: center;
      top: -2rpx;
      margin-right: 6rpx;
    }
    &__title {
    }
    /* 标题 end */

    /* 标签 start */
    &__tags-container {
      display: flex;
      flex-direction: row;
      flex-wrap: nowrap;
      align-items: center;
      justify-content: flex-start;
    }
    &__tag {
      margin: 10rpx;
      color: #ff7043;
      border: 2rpx solid #ff7043;
      padding: 0 6rpx;
      border-radius: 10rpx;
      font-size: 20rpx;

      &:first-child {
        margin-left: 0rpx !important;
      }
    }
    /* 标签 end */

    /* 价格 start */
    &__price-container {
      padding: 10rpx 0;
      font-size: 24rpx;
      font-weight: bold;
    }
    &__price {
      &--unit {
      }
      &--integer {
        font-size: 38rpx;
      }
      &--decimal {
      }
    }
    /* 价格 end */
    /* 内容 end */
  }
}

/* 商家商品 start*/
.tn-blogger-content {
  &__wrap {
    box-shadow: 0rpx 0rpx 50rpx 0rpx rgba(0, 0, 0, 0.07);
    border-radius: 20rpx;
    margin: 15rpx;
  }

  &__info {
    &__btn {
      margin-right: -12rpx;
      opacity: 0.5;
    }
  }

  &__label {
    &__item {
      line-height: 45rpx;
      padding: 0 10rpx;
      margin: 5rpx 18rpx 0 0;

      &--prefix {
        color: #e83a30;
        padding-right: 10rpx;
      }
    }

    &__desc {
      line-height: 35rpx;
    }
  }

  &__main-image {
    border-radius: 16rpx 16rpx 0 0;

    &--1 {
      max-width: 690rpx;
      min-width: 690rpx;
      max-height: 400rpx;
      min-height: 400rpx;
    }

    &--2 {
      max-width: 260rpx;
      max-height: 260rpx;
    }

    &--3 {
      height: 212rpx;
      width: 100%;
    }
  }

  &__count-icon {
    font-size: 24rpx;
    padding-right: 5rpx;
  }
}

.image-book {
  padding: 150rpx 0rpx;
  font-size: 16rpx;
  font-weight: 300;
  position: relative;
}
.image-picbook {
  background-size: cover;
  background-repeat: no-repeat;
  // background-attachment:fixed;
  background-position: top;
  border-radius: 15rpx 15rpx 0 0;
}

/* 商家头像 start */
.logo-image {
  width: 40rpx;
  height: 40rpx;
  position: relative;
}

.logo-pic {
  background-size: cover;
  background-repeat: no-repeat;
  // background-attachment:fixed;
  background-position: top;
  border: 2rpx solid rgba(255, 255, 255, 0.05);
  box-shadow: 0rpx 0rpx 80rpx 0rpx rgba(0, 0, 0, 0.15);
  border-radius: 50%;
  overflow: hidden;
  // background-color: #FFFFFF;
}

/* 商家商品 end*/

.goods-info {
  display: flex;
  flex-direction: column;
  gap: 8rpx;

  .goods-title {
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
    line-height: 1.4;
  }

  .goods-price {
    font-size: 32rpx;
    color: #ff4444;
    font-weight: bold;
  }

  .goods-sales {
    font-size: 24rpx;
    color: #999;
  }
}

/* 过期样式 */
.expired {
  opacity: 0.6;
  filter: grayscale(100%);
  position: relative;
}

.expired-mark {
  position: absolute;
  top: 20rpx;
  right: 20rpx;
  background-color: rgba(0, 0, 0, 0.6);
  color: #fff;
  padding: 4rpx 16rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
}
</style>

